package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.po.SysMQMessage;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/*
 * @className: SysMQMessageMapper
 * @author: chentao
 * @date: 2025/2/28 下午5:17
 * @Version: 1.0
 * @description:
 */
@Mapper
public interface SysMQMessageMapper extends BaseMapper<SysMQMessage> {

    @Select("select count(*) from sys_mq_message where server_key =#{serverKey} and status = 0")
    public int getSysMQMessageTotalSize(@Param("serverKey") long serverKey);

    @Select("select * from sys_mq_message where server_key =#{serverKey} and status = 0 and ((retry_count = 0) or (retry_count < #{maxRetryCount} and retry_time < now())) order by id asc LIMIT #{maxSize}")
    public List<SysMQMessage> getSysMQMessage(@Param("serverKey") Long serverKey, @Param("maxSize") int maxSize, @Param("maxRetryCount") int maxRetryCount);

    @Update("update sys_mq_message set server_key =#{targetServerKey} where server_key =#{sourceServerKey} and status = 0")
    public void updateMessageServer(@Param("sourceServerKey") Long sourceServerKey, @Param("targetServerKey") Long targetServerKey);

    @Update("update sys_mq_message set server_key = #{targetServerKey} where server_key =#{sourceServerKey} and `status` = 0 and id % #{total} = #{index} ")
    public void updateAllMessageServerBatch(@Param("sourceServerKey") Long sourceServerKey, @Param("targetServerKey") Long targetServerKey, @Param("index") int index, @Param("total") int total);

    @Select("<script>" + " select DISTINCT server_key from sys_mq_message where status = 0 and server_key not in ( " + " <foreach collection='activeServerKeys' separator=',' item='id'>" + " #{id} " + " </foreach> " + " )</script>")
    public List<Long> getMessageServerKeys(@Param("activeServerKeys") List<Long> activeServerKeys);

    @Select("select DISTINCT server_key from sys_mq_message where status = 0")
    public List<Long> getAllMessageServer();

    @Update(value = "update sys_mq_message set server_key = #{targetServerKey} where server_key is null order by id asc LIMIT #{countSize}")
    public void updateMessageServerBatch(@Param("targetServerKey") Long targetServerKey, @Param("countSize")int countSize);
}
